package com.aidex.system.service.impl;

import com.aidex.common.core.domain.entity.SysPost;
import com.aidex.common.core.domain.entity.SysRole;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.service.impl.BasicServiceImpl;
import com.aidex.common.exception.BizException;
import com.aidex.common.exception.CustomException;
import com.aidex.common.utils.PinYin4JCn;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.spring.SpringUtils;
import com.aidex.framework.cache.ConfigUtils;
import com.aidex.framework.cache.UserUtils;
import com.aidex.system.common.SysErrorCode;
import com.aidex.system.domain.SysUserPost;
import com.aidex.system.domain.SysUserRole;
import com.aidex.system.mapper.*;
import com.aidex.system.service.SysUserService;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

/**
 * 用户 业务层处理
 */
@Service
public class SysUserServiceImpl extends BasicServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired(required = false)
    private SysRoleMapper roleMapper;

    @Autowired(required = false)
    private SysPostMapper postMapper;

    @Autowired(required = false)
    private SysUserRoleMapper userRoleMapper;

    @Autowired(required = false)
    private SysUserPostMapper userPostMapper;

    @Override
    public SysUser selectUserByUserName(String userName) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", userName);
        return mapper.selectOne(wrapper);
    }

    @Override
    public String selectUserRoleGroup(String userName) {
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        wrapper.eq("u.name", userName);
        List<SysRole> list = roleMapper.selectListByUser(wrapper);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public String selectUserPostGroup(String userName) {
        QueryWrapper<SysPost> wrapper = new QueryWrapper<>();
        wrapper.eq("u.userName", userName);
        List<SysPost> list = postMapper.selectListByUser(wrapper);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    @Override
    public void checkUserNameUnique(SysUser user) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", user.getUserName());
        wrapper.ne("id", user.getId());
        if (mapper.selectCount(wrapper) > 0) {
            throw new BizException(SysErrorCode.B_SYSUSER_UserNameAlreadyExist);
        }
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public void checkPhoneUnique(SysUser user) {
        if (StringUtils.isNotBlank(user.getPhonenumber())) {
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("phonenumber", user.getPhonenumber());
            wrapper.ne("id", user.getId());
            if (mapper.selectCount(wrapper) > 0) {
                throw new BizException(SysErrorCode.B_SYSUSER_PhoneAlreadyExist);
            }
        }
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public void checkEmailUnique(SysUser user) {
        if (StringUtils.isNotBlank(user.getEmail())) {
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("email", user.getEmail());
            wrapper.ne("id", user.getId());
            if (mapper.selectCount(wrapper) > 0) {
                throw new BizException(SysErrorCode.B_SYSUSER_EmailAlreadyExist);
            }
        }
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getId()) && user.isAdmin()) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insert(SysUser user) {
        checkUserNameUnique(user);
        checkPhoneUnique(user);
        checkEmailUnique(user);
        if (StringUtils.isBlank(user.getPassword())) {
            String password = ConfigUtils.getConfigValueByKey("sys.user.initPassword", "123456");
            user.setPassword(password);
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if (StringUtils.isNotEmpty(user.getName())) {
            user.setUserPinyin(PinYin4JCn.getFullAndSimplePinYin(user.getName(), 500));
        }

        // 新增用户信息
        int result = super.insert(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return result;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateById(SysUser user) {
        checkUserNameUnique(user);
        checkPhoneUnique(user);
        checkEmailUnique(user);
        String userId = user.getId();
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("user_id", userId);
        // 删除用户与角色关联
        userRoleMapper.delete(wrapper);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.delete(wrapper);
        // 新增用户与岗位管理
        insertUserPost(user);
        if (StringUtils.isNotEmpty(user.getName())) {
            user.setUserPinyin(PinYin4JCn.getFullAndSimplePinYin(user.getName(), 500));
        }
        return super.updateById(user);
    }

    @Override
    @Transactional
    public void insertUserRole(SysUser user) {
        String[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            for (String roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getId());
                ur.setRoleId(roleId);
                userRoleMapper.insert(ur);
            }
        }
    }

    /**
     * 新增用户岗位信息sy
     *
     * @param user 用户对象
     */
    @Override
    @Transactional
    public void insertUserPost(SysUser user) {
        String[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            for (String postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getId());
                up.setPostId(postId);
                userPostMapper.insert(up);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteById(Serializable userId) {
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("user_id", userId);
        // 删除用户与角色关联
        userRoleMapper.delete(wrapper);
        // 删除用户与岗位表
        userPostMapper.delete(wrapper);
        return super.deleteById(userId);
    }

    @Override
    @Transactional
    public int deleteBatchIds(Collection<? extends Serializable> idList) {
        int flag = 0;
        for (Serializable userId : idList) {
            flag += deleteById(userId);
        }
        return flag;
    }

    @Override
    @Transactional
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = ConfigUtils.getConfigValueByKey("sys.user.initPassword", "123456");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insert(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    user.setUpdateBy(operName);
                    this.updateById(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    @Transactional
    public boolean insertRoleUser(SysUserRole sysUserRole) {
        String[] userIds = sysUserRole.getUserId().split(";");
        String roleId = sysUserRole.getRoleId();
        for (String userId : userIds) {
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(userId);
            try{
                userRoleMapper.insert(userRole);
            }catch (Exception e) {

            }
        }
        return true;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean registerUser(SysUser user) {
        return mapper.insert(user) > 0;
    }

    /**
     * 刷新缓存
     *
     * @return 结果
     */
    @Override
    public void refreshCache() {
        UserUtils.clearUserCache();
        loadingUserCache();
    }

    @Override
    public void loadingUserCache() {
        List<SysUser> userList = selectList(new QueryWrapper<>());
        for (SysUser sysUser : userList) {
            UserUtils.setUserCache(sysUser);
        }
    }

    @Override
    @Transactional
    public int resetUserPwd(String userName, String encryptPassword) {
        UpdateWrapper<SysUser> wrapper = new UpdateWrapper<>();
        wrapper.set("password", encryptPassword);
        wrapper.eq("name", userName);
        SysUser user = new SysUser();
        user.setPassword(encryptPassword);
        return mapper.update(user, wrapper);
    }

    @Override
    public void checkUserDataScope(String userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("id", userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectList(wrapper);
            if (StringUtils.isEmpty(users)) {
                throw new BizException("没有权限访问用户数据！");
            }
        }
    }

    @Override
    public IPage<SysUser> selectPageByRoleId(IPage<SysUser> page, QueryWrapper<SysUser> queryWrapper) {
        return mapper.selectPageByRoleId(page, queryWrapper);
    }
}
